const commandLineArgs = require('command-line-args')
const chalk = require('chalk')
const fs = require('fs')

const optionDefinitions = [
  { name: 'handle', alias: 'h', type: String, description: '操作类型, 例如 create, delete' },
  { name: 'content', alias: 'c', type: String, description: '内容类型, 例如 list, detail' },
  { name: 'filename', alias: 'n', type: String, description: '文件名称, 例如 channel.jsx, list.vue' },
  { name: 'path', alias: 'p', type: String, description: '目标路径, 例如 Setting, Prodocut' },
]

const runOptions = {
  handle: 'create',
  content: 'list',
  filename: 'list.jsx',
  path: 'Setting',
  ...commandLineArgs(optionDefinitions)
}

function validateFile(url) {
  const hasFile = fs.existsSync(url)
  if (!hasFile) {
    const msg = '未查询到指定目录'
    console.log(chalk.red(msg))
  }
  return hasFile
}

function createFile() {
  const { content, filename, path } = runOptions
  const fileType = filename.indexOf('.') ? filename.split('.').pop() : ''
  const code = fs.readFileSync(`${__dirname}/${content}.${fileType}`, 'utf-8')
  const filePath = `src/views/${path}`
  if (!validateFile(filePath)) return
  fs.writeFileSync(`${filePath}/${filename}`, code, err => console.log(chalk.red(err)))
  console.log(chalk.green(`创建完成! ${filePath}/${filename}`))
}

function deleteFile() {
  const { path } = runOptions
  const filePath = `src/views/${path}`
  if (!validateFile(filePath)) return
  fs.unlinkSync(filePath)
  console.log(chalk.green(`删除成功! ${filePath}`))
}

function main() {
  try {
    const { handle } = runOptions
    switch (handle) {
      case 'create':
        createFile()
        break
      case 'delete':
        deleteFile()
        break
    }
  } catch (error) {
    console.error(chalk.red(error))
  }
}

main()
